import { createRouter, createWebHashHistory } from 'vue-router'
import useSettingsStore from '@/store/modules/settings'
import useKeepAliveStore from '@/store/modules/keepAlive'

/* import '@/assets/styles/nprogress.scss'
import { useNProgress } from '@vueuse/integrations/useNProgress'
const { isLoading } = useNProgress() */

const settingsStore = useSettingsStore()
// 路由相关数据
import { constantRoutes } from './routes'

const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes
})
router.beforeEach(async(to, from, next) => {
    settingsStore.setRouterChangeEnd(false)
    settingsStore.setShowLogoState(to.name === 'Home')

    // document.title = to.meta.title
    next()
})

router.afterEach((to, from) => {
    settingsStore.setRouterChangeEnd(true)
    const keepAliveStore = useKeepAliveStore()
    document.body.scrollTop = 0
    document.documentElement.scrollTop = 0
    // settingsStore.app.enableProgress && (isLoading.value = false)
    // 设置页面 title
    to.meta.title && settingsStore.setTitle(typeof to.meta.title === 'function' ? to.meta.title() : to.meta.title)
    // 判断当前页面是否开启缓存，如果开启，则将当前页面的 name 信息存入 keep-alive 全局状态
    if (to.meta.cache) {
        // let componentName = to.matched[to.matched.length - 1].components.default.name
        let componentName = to.matched[to.matched.length - 1].name
        if (componentName) {
            keepAliveStore.add(componentName)
        } else {
            console.warn('该页面组件未设置组件名，会导致缓存失效，请检查')
        }
    }
    // 判断离开页面是否开启缓存，如果开启，则根据缓存规则判断是否需要清空 keep-alive 全局状态里离开页面的 name 信息
    if (from.meta.cache) {
        // let componentName = from.matched[from.matched.length - 1].components.default.name
        let componentName = from.matched[from.matched.length - 1].name
        // 通过 meta.cache 判断针对哪些页面进行缓存
        switch (typeof from.meta.cache) {
            case 'string':
                if (from.meta.cache != to.name) {
                    keepAliveStore.remove(componentName)
                }
                break
            case 'object':
                if (!from.meta.cache.includes(to.name)) {
                    keepAliveStore.remove(componentName)
                }
                break
        }
        // 如果进入的是 reload 页面，则也将离开页面的缓存清空
        if (to.name == 'reload') {
            keepAliveStore.remove(componentName)
        }
    }

    /* const { title, keywords, description } = to.meta
    if (title) {
        document.title = title
    }
    if (keywords) {
        const metaKeywords = document.querySelector('meta[name="keywords"]')
        if (metaKeywords) {
            metaKeywords.content = keywords
        }
    }
    if (description) {
        const metaDescription = document.querySelector('meta[name="description"]')
        if (metaDescription) {
            metaDescription.content = description
        }
    } */
})

export default router
